class Calculator {
  constructor() {
    this.display = document.querySelector('.display');
    this.expressionElement = document.querySelector('.expression');
    this.expression = '';
    this.currentValue = '0';
    this.previousValue = null;
    this.operator = null;
    this.shouldResetDisplay = false;

    this.initEventListeners();
  }

  initEventListeners() {
    document.querySelectorAll('[data-number]').forEach(button => {
      button.addEventListener('click', (e) => this.handleNumber(e.target.dataset.number));
    });

    document.querySelectorAll('[data-operator]').forEach(button => {
      button.addEventListener('click', (e) => this.handleOperator(e.target.dataset.operator));
    });

    document.querySelector('[data-action="calculate"]').addEventListener('click', () => this.calculate());
    document.querySelector('[data-action="clear"]').addEventListener('click', () => this.clear());
    document.querySelector('[data-action="backspace"]').addEventListener('click', () => this.backspace());
  }

  handleNumber(number) {
    if (this.shouldResetDisplay) {
      this.expression += this.currentValue + ' ';
      this.currentValue = '';
      this.shouldResetDisplay = false;
    }
    
    if (number === '.' && this.currentValue.includes('.')) return;
    
    this.currentValue = this.currentValue === '0' && number !== '.' 
      ? number 
      : this.currentValue + number;
    
    if (this.operator) {
      this.expression = `${this.previousValue} ${this.operator} ${this.currentValue}`;
    } else {
      this.expression = this.currentValue;
    }
    this.expressionElement.textContent = this.expression;
    
    this.updateDisplay();
  }

  handleOperator(operator) {
    if (this.operator && !this.shouldResetDisplay) {
      this.calculate();
    }
    
    if (this.operator && this.previousValue) {
      this.expression = `${this.previousValue} ${this.operator} ${this.currentValue} ${operator} `;
    } else {
      this.expression = `${this.currentValue} ${operator} `;
    }
    this.expressionElement.textContent = this.expression;
    this.previousValue = this.currentValue;
    this.operator = operator;
    this.shouldResetDisplay = true;
  }

  calculate() {
    if (!this.operator || !this.previousValue) return;

    const prev = parseFloat(this.previousValue);
    const current = parseFloat(this.currentValue);
    let result;

    try {
      switch(this.operator) {
        case '+': result = prev + current; break;
        case '-': result = prev - current; break;
        case '×': result = prev * current; break;
        case '÷': 
          if (current === 0) throw new Error('除零错误');
          result = prev / current;
          break;
        case '%': result = prev % current; break;
      }
      
      if (isNaN(result) || !isFinite(result)) throw new Error('无效计算');
      
      this.currentValue = String(result);
      this.expression = `${this.expression} = ${this.currentValue}`;
      this.expressionElement.textContent = this.expression;
      this.updateDisplay();
      this.previousValue = null;
      this.operator = null;
    } catch (error) {
      this.handleError(error.message);
    }
    
    this.operator = null;
    this.shouldResetDisplay = true;
  }

  clear() {
    this.expression = '';
    this.expressionElement.textContent = this.expression;
    this.currentValue = '0';
    this.previousValue = null;
    this.operator = null;
    this.shouldResetDisplay = false;
    document.querySelector('.expression').textContent = this.expression;
    this.updateDisplay();
  }

  backspace() {
    if (this.currentValue.length > 1) {
      this.currentValue = this.currentValue.slice(0, -1);
    } else {
      this.currentValue = '0';
    }
    this.updateDisplay();
  }

  updateDisplay() {
    this.display.textContent = this.currentValue.length > 10 
      ? parseFloat(this.currentValue).toExponential(5) 
      : this.currentValue;
  }

  handleError(message) {
    this.display.textContent = message;
    setTimeout(() => {
      this.clear();
    }, 1500);
  }
}

// 初始化计算器
new Calculator();